/**
 * Created by zhulingxiao on 2017/6/7.
 */
import { myFetch } from '../../utils/func'

import { tableLoading, tableFinish } from './table'

export const MENU_UPDATE = 'MENU_UPDATE';

export const menuFetch = (cb = function () {} ) => {

  return dispatch => {

    dispatch(tableLoading())

    return myFetch('/Menu/SearchmyMenuList',{})

      .then(data=>{

        let sideMenu = data.data;

        for(let i in sideMenu){

          sideMenu[i].key = i;

          let children = sideMenu[i].children;

          for(let j in children){

            children[j].key ='' + children[j].title + children[j].index;

            delete children[j].children;

          }

        }

        dispatch({ type : MENU_UPDATE, data : sideMenu})

        dispatch(tableFinish())

        cb(sideMenu)

      })

  }

}

export const menuDelete = (sysid) => {

  return dispatch => {

    return myFetch('/Menu/DeleteMenu',{
      menuid:sysid
    })

      .then(()=>{

        dispatch(menuFetch())


      })

  }

}

export const menuUpdate = (data) => {

  return dispatch => {

    return myFetch('/Menu/UpdateMenu',{
      sysID:data.sysid,
      title:data.title,
      icon:data.icon,
      link:data.link,
      qx:data.qx,
      index:data.index
    })

      .then(()=>{

        dispatch(menuFetch())

      })

  }

}

export const menuAdd = (data) => {

  return dispatch => {

    return myFetch('/Menu/AddMenu', {
      title: data.title,
      icon: data.icon,
      link: data.link,
      qx: data.qx,
      index: data.index,
      parentid: data.parentid
    })

      .then(() => {

        dispatch(menuFetch())

      })
  }
}

